<template>
  <div
    ref="chartRef"
    :style="{ width: chartWidth, height: chartHeight }"
    class="bar-chart"
  ></div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      categories: ['产品A', '产品B', '产品C', '产品D', '产品E'],
      series: [
        {
          name: '销量',
          data: [320, 302, 301, 334, 390]
        }
      ]
    })
  },
  title: {
    type: String,
    default: '柱状图'
  },
  width: {
    type: String,
    default: '400px'
  },
  height: {
    type: String,
    default: '300px'
  }
})

const chartRef = ref(null)
const chartInstance = ref(null)

const chartWidth = ref(props.width)
const chartHeight = ref(props.height)

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance.value = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return

  const option = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      top: '30px',
      data: props.data.series?.map(item => item.name) || []
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '80px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.data.categories || []
    },
    yAxis: {
      type: 'value'
    },
    series: props.data.series?.map(item => ({
      name: item.name,
      type: 'bar',
      data: item.data,
      itemStyle: {
        borderRadius: [4, 4, 0, 0]
      }
    })) || []
  }

  chartInstance.value.setOption(option)
}

// 监听数据变化
watch(() => props.data, () => {
  updateChart()
}, { deep: true })

watch(() => props.title, () => {
  updateChart()
})

// 监听尺寸变化
watch(() => props.width, (newVal) => {
  chartWidth.value = newVal
  nextTick(() => {
    chartInstance.value?.resize()
  })
})

watch(() => props.height, (newVal) => {
  chartHeight.value = newVal
  nextTick(() => {
    chartInstance.value?.resize()
  })
})

onMounted(() => {
  initChart()
})
</script>

<style lang="scss" scoped>
.bar-chart {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}
</style>
